package com.freeLearning.boot.system.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.freeLearning.boot.common.enums.AuditStatusEnum;
import com.freeLearning.boot.common.result.Result;
import com.freeLearning.boot.core.security.util.SecurityUtils;
import com.freeLearning.boot.course.model.entity.CourseReview;
import com.freeLearning.boot.course.model.entity.CourseReviewAuditHistory;
import com.freeLearning.boot.course.model.query.CourseReviewPageQuery;
import com.freeLearning.boot.system.enums.MessageEnum;
import com.freeLearning.boot.system.mapper.ConsultantReviewAuditHistoryMapper;
import com.freeLearning.boot.system.model.entity.ConsultantReview;
import com.freeLearning.boot.system.model.entity.ConsultantReviewAuditHistory;
import com.freeLearning.boot.system.model.entity.Message;
import com.freeLearning.boot.system.model.entity.UserRole;
import com.freeLearning.boot.system.service.ConsultantReviewService;
import com.freeLearning.boot.system.service.MessageService;
import com.freeLearning.boot.system.service.UserRoleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Tag(name = "26.课程评论")
@RequestMapping("/api/v1/consultant/review")
@RestController
@RequiredArgsConstructor
public class ConsultantReviewController {
    private final ConsultantReviewService consultantReviewService;
    private final ConsultantReviewAuditHistoryMapper consultantReviewAuditHistoryMapper;
    private final UserRoleService userRoleService;
    private final MessageService messageService;
    @Operation(summary = "分页查询咨询师评价")
    @PostMapping("/page")
    public Result<IPage<ConsultantReview>> page(@RequestBody CourseReviewPageQuery courseReviewPageQuery) {
        int pageNum = courseReviewPageQuery.getPageNum();
        int pageSize = courseReviewPageQuery.getPageSize();
        Page<ConsultantReview> page = new Page<>(pageNum, pageSize);
        IPage<ConsultantReview> pages = this.consultantReviewService.page(page, new LambdaUpdateWrapper<ConsultantReview>()
                .eq(courseReviewPageQuery.getUserId() != null ,ConsultantReview::getUserId, courseReviewPageQuery.getUserId())
                .eq(courseReviewPageQuery.getStatus() != null ,ConsultantReview::getStatus, courseReviewPageQuery.getStatus())
                .eq(courseReviewPageQuery.getConsultantId() != null ,ConsultantReview::getConsultantId, courseReviewPageQuery.getConsultantId())
                .like(courseReviewPageQuery.getKeyword() != null && !courseReviewPageQuery.getKeyword().equals(""), ConsultantReview::getComment, courseReviewPageQuery.getKeyword())
                .orderByDesc(ConsultantReview::getReviewTime)
        );
        return Result.success(pages);
    }

    @Operation(summary = "新增咨询师评价")
    @PostMapping("/add")
    public Result<Boolean> add(@RequestBody ConsultantReview consultantReview) {
        consultantReview.setAuditInfo("咨询师评价新增初审");
        boolean save = this.consultantReviewService.save(consultantReview);
        ConsultantReviewAuditHistory history = ConsultantReviewAuditHistory.builder()
                .reviewId(consultantReview.getId())
                .auditTime(LocalDateTime.now())
                .opinion("新增咨询师评论初审")
                .auditorName(SecurityUtils.getNickName())
                .status(AuditStatusEnum.WAIT_AUDIT.getValue())
                .auditorId(SecurityUtils.getUserId())
                .build();
        consultantReviewAuditHistoryMapper.insert(history);
        sendReviewAuditMessage(consultantReview,true);
        return Result.success(save);
    }

    @Operation(summary = "删除咨询师评价")
    @DeleteMapping("/delete/{id}")
    public Result<Boolean> delete(@PathVariable Long id) {
        return Result.success(this.consultantReviewService.removeById(id));
    }

    @Operation(summary = "更新咨询师评价")
    @PutMapping("/update")
    public Result<Boolean> update(@RequestBody ConsultantReview consultantReview) {
        consultantReview.setStatus(AuditStatusEnum.WAIT_AUDIT.getValue());
        boolean b = this.consultantReviewService.updateById(consultantReview);
        ConsultantReviewAuditHistory history = ConsultantReviewAuditHistory.builder()
                .reviewId(consultantReview.getId())
                .auditorName(SecurityUtils.getNickName())
                .auditTime(LocalDateTime.now())
                .opinion("审核咨询师评论")
                .status(AuditStatusEnum.WAIT_AUDIT.getValue())
                .auditorId(SecurityUtils.getUserId())
                .build();
        consultantReviewAuditHistoryMapper.insert(history);
        sendReviewAuditMessage(consultantReview,false);
        return Result.success();
    }

    @Operation(summary = "审核咨询师评价")
    @PutMapping("/audit")
    public Result<Boolean> audit(@RequestBody ConsultantReview consultantReview) {
        Long userId = SecurityUtils.getUserId();
        if (Objects.equals(consultantReview.getStatus(), AuditStatusEnum.AUDIT_PASS.getValue())) {
            Message message = Message.builder()
                    .title("您收到一条新的咨询评价")
                    .content("用户:" + consultantReview.getNickName() + "评论了您")
                    .type(MessageEnum.CONSULTANT_REVIEW.getValue())
                    .publisherId(consultantReview.getUserId())
                    .publishTime(LocalDateTime.now())
                    .createBy(userId)
                    .other(JSONUtil.toJsonStr(consultantReview))
                    .acceptId(consultantReview.getConsultantId())
                    .build();
            messageService.sendMessage(message);
            consultantReview.setAuditInfo("审核通过！");
        } else {
            Message message = Message.builder()
                    .title("评价未通过")
                    .content("您评价的咨询师未通过审核，原因：" + consultantReview.getAuditInfo())
                    .type(MessageEnum.REVIEW_AUDIT_NOT_PASS.getValue())
                    .publisherId(userId)
                    .publishTime(LocalDateTime.now())
                    .createBy(userId)
                    .other(JSONUtil.toJsonStr(consultantReview))
                    .acceptId(consultantReview.getUserId())
                    .build();
            messageService.sendMessage(message);
        }
        ConsultantReviewAuditHistory courseReviewAuditHistory = ConsultantReviewAuditHistory.builder()
                .reviewId(consultantReview.getId())
                .status(consultantReview.getStatus())
                .opinion(consultantReview.getAuditInfo())
                .auditorId(SecurityUtils.getUserId())
                .auditorName(SecurityUtils.getNickName())
                .auditTime(LocalDateTime.now())
                .build();
        consultantReviewAuditHistoryMapper.insert(courseReviewAuditHistory);
        return Result.success(this.consultantReviewService.updateById(consultantReview));
    }
    public void sendReviewAuditMessage(ConsultantReview consultantReview, Boolean isAdd) {
        List<UserRole> adminList = userRoleService.list(new LambdaQueryWrapper<UserRole>().eq(UserRole::getRoleId, 2));
        StringBuilder content = new StringBuilder();
        content
                .append("用户：")
                .append(consultantReview.getNickName());

        if (isAdd) {
            content.append("评论了咨询师")
                    .append(consultantReview.getConsultantName())
                    .append(",请尽快审核！");
        } else {
            content.append(",修改了对咨询师")
                    .append(consultantReview.getConsultantName())
                    .append("的评价，请尽快审核！");
        }
        adminList.forEach(item -> {
            Message message = Message.builder()
                    .title("有新的评价需要审核")
                    .content(content.toString())
                    .type(MessageEnum.CONSULTANT_REVIEW_AUDIT.getValue())
                    .publisherId(consultantReview.getUserId())
                    .publishTime(LocalDateTime.now())
                    .createBy(consultantReview.getUserId())
                    .acceptId(item.getUserId())
                    .build();
            messageService.sendMessage(message);
        });
    }

    @Operation(summary = "查询审核历史")
    @GetMapping("/review/audit/history/{reviewId}")
    public Result<List<ConsultantReviewAuditHistory>> auditList(@PathVariable Integer reviewId) {
        return Result.success(consultantReviewAuditHistoryMapper.selectList(new LambdaQueryWrapper<ConsultantReviewAuditHistory>().eq(ConsultantReviewAuditHistory::getReviewId, reviewId)));
    }
}
